package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.base.BasePage;
import com.chexiehui.jc.entity.CarSeriesInfo;
import com.chexiehui.jc.entity.DictInfo;
import com.chexiehui.jc.entity.PriceConditionInfo;
import com.chexiehui.jc.mvp.car.SalesRankingListCovenant;
import com.chexiehui.jc.mvp.car.SalesRankingListPresenter;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.CustomChooseCarTypePopup;
import com.chexiehui.jc.widget.CustomChoosePricePopup;
import com.chexiehui.jc.widget.LoadingLayout;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 销量排行列表
 */
public class SalesRankingListActivity extends BaseMvpActivity<SalesRankingListPresenter> implements SalesRankingListCovenant.View,
        CustomChoosePricePopup.ICustomChoosePricePopupListener, CustomChooseCarTypePopup.ICustomChooseCarTypeListener {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_choose_time)
    TextView tvChooseTime;
    @BindView(R.id.tv_choose_price)
    TextView tvChoosePrice;
    @BindView(R.id.ll_choose_panel)
    LinearLayout llChoosePanel;
    @BindView(R.id.v_split_line)
    View v_split_line;
    @BindView(R.id.nsgv_type_choose_grid)
    NonSlidingGridView nsgvTypeChooseGrid;
    @BindView(R.id.hsv_type_scroller)
    HorizontalScrollView hsvTypeScroller;

    private List<DictInfo> bigTypeData;
    private com.zhy.adapter.abslistview.CommonAdapter<DictInfo> bigTypeAdapter;
    private List<CarSeriesInfo> listData;
    private CommonAdapter<CarSeriesInfo> listAdapter;
    private BasePage<CarSeriesInfo> page;
    private Date selectDate;
    private CustomChoosePricePopup customChoosePricePopup;
    private CustomChooseCarTypePopup customChooseCarTypePopup;
    private PriceConditionInfo choosePrice;
    private TimePickerView pvTimePicker;
    private String chooseSeriesType = "";
    private int chooseBigTypePosition = 0;
    private int tempPosition = -1;

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("销量排行")
                .setDividerVisible(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_sales_ranking_list;
    }

    @Override
    protected void initView(Bundle var1) {
        loadingLayout.setStatus(LoadingLayout.Loading);
        selectDate = TimeUtils.getNowDate();
        tvChooseTime.setText(TimeUtils.date2String(selectDate, new SimpleDateFormat("yyyy年MM月")));
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        loadingLayout.setOnReloadListener(v -> {
            refreshLayout.finishRefresh(false);
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        });
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (loadingLayout.getStatus() == LoadingLayout.Loading) {
                    refreshLayout.finishRefresh(false);
                    return;
                }
                mvpPresenter.getList(1);
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (page != null && page.getTotalRecordCount() > listData.size()) {
                    mvpPresenter.getList(page.getPageIndex() + 1);
                } else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        recycler.setLayoutManager(new LinearLayoutManager(mContext));

        listData = new ArrayList<>();
        listAdapter = new CommonAdapter<CarSeriesInfo>(mContext, R.layout.item_sales_ranking, listData) {
            @Override
            protected void convert(ViewHolder holder, CarSeriesInfo item, int position) {
                GlideUtil.loadImageViewCrop(mContext, item.getImg(), holder.getView(R.id.iv_item_image),
                        R.drawable.shape_square, R.drawable.shape_square);
                holder.setText(R.id.tv_item_name, item.getName());
                holder.setText(R.id.tv_item_price, item.getPriceMaxMinStr());
                holder.setText(R.id.tv_item_rank_count, item.getSalesvolume() + "");
                if (position > 2) {
                    holder.getView(R.id.iv_item_rank_tag).setVisibility(View.GONE);
                    holder.setTextColor(R.id.tv_item_rank_num, ContextCompat.getColor(mContext, R.color.c_333333));
                    holder.setVisible(R.id.tv_item_rank_num, true);
                    holder.setText(R.id.tv_item_rank_num, (position + 1) + "");
                } else {
                    holder.getView(R.id.iv_item_rank_tag).setVisibility(View.VISIBLE);
                    holder.setVisible(R.id.tv_item_rank_num, false);
                    holder.setTextColor(R.id.tv_item_rank_num, ContextCompat.getColor(mContext, R.color.colorWhite));
                    if (position == 0) {
                        holder.setImageResource(R.id.iv_item_rank_tag, R.mipmap.ic_rank_1);
                    } else if (position == 1) {
                        holder.setImageResource(R.id.iv_item_rank_tag, R.mipmap.ic_rank_2);
                    } else if (position == 2) {
                        holder.setImageResource(R.id.iv_item_rank_tag, R.mipmap.ic_rank_3);
                    }
                }
            }
        };
        listAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (NoDoubleClickUtils.isDoubleClick()) return;
                startActivity(CarSeriesDetailsActivity.class,
                        new BundleBuilder().putString("seriesId", listData.get(position).getId())
                                .create());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        recycler.setAdapter(listAdapter);

        bigTypeData = new ArrayList<>();
        bigTypeAdapter = new com.zhy.adapter.abslistview.CommonAdapter<DictInfo>(mContext, R.layout.item_sales_ranking_type, bigTypeData) {
            @Override
            protected void convert(com.zhy.adapter.abslistview.ViewHolder viewHolder, DictInfo item, int position) {
                TextView tv_item_name = viewHolder.getView(R.id.tv_item_name);
                tv_item_name.setText(item.getValue());
                tv_item_name.setTextColor(ContextCompat.getColor(mContext, chooseBigTypePosition == position ? R.color.app_color : R.color.c_333333));
                viewHolder.setImageResource(R.id.iv_item_icon, item.getIcon());
            }
        };
        nsgvTypeChooseGrid.setAdapter(bigTypeAdapter);
        nsgvTypeChooseGrid.setOnItemClickListener((parent, view, position, id) -> {
            if(chooseBigTypePosition == position){
                if(bigTypeData.get(position).getChildList() != null && bigTypeData.get(position).getChildList().size() > 0){
                    showChooseTypePopup(bigTypeData.get(position).getChildList());
                }
                return;
            }
            chooseBigTypePosition = position;
            bigTypeAdapter.notifyDataSetChanged();
            if(position == 0){
                chooseSeriesType = "";
                loadingLayout.setStatus(LoadingLayout.Loading);
                mvpPresenter.getList(1);
                return;
            }
            if(bigTypeData.get(position).getChildList() == null){
                tempPosition = position;
                mvpPresenter.getSmallType(bigTypeData.get(tempPosition).getKey());
            }else{
                if(bigTypeData.get(position).getChildList().size() > 0){
                    showChooseTypePopup(bigTypeData.get(position).getChildList());
                }else{
                    chooseSeriesType = bigTypeData.get(position).getKey();
                    loadingLayout.setStatus(LoadingLayout.Loading);
                    mvpPresenter.getList(1);
                }
            }
        });
        hsvTypeScroller.setVisibility(View.GONE);

        mvpPresenter.getBigType();
        mvpPresenter.getList(1);
    }

    @Override
    protected SalesRankingListPresenter createPresenter() {
        return new SalesRankingListPresenter(this);
    }

    @Override
    public void onGetListSuccess(BaseModel<BasePage<CarSeriesInfo>> successResult) {
        page = successResult.getData();
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        } else if (refreshLayout.getState() == RefreshState.Loading) {
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
            if (page.getTotalRecordCount() <= listAdapter.getDatas().size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        } else {
            refreshLayout.finishRefresh(true);
            listAdapter.getDatas().clear();
            listAdapter.getDatas().addAll(page.getItems());
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetListFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(true);
                if (listAdapter.getDatas().size() > 0) {
                    listAdapter.getDatas().clear();
                    listAdapter.notifyDataSetChanged();
                }
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            } else if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                loadingLayout.setStatus(LoadingLayout.Empty);
                loadingLayout.setEmptyText(failureResult.getResultInfo());
            }
        } else {
            if (refreshLayout.getState() == RefreshState.Refreshing) {
                refreshLayout.finishRefresh(false);
            }
            if (refreshLayout.getState() == RefreshState.Loading) {
                refreshLayout.finishLoadMore(false);
            }
            if (listAdapter.getDatas().size() <= 0) {
                loadingLayout.setStatus(LoadingLayout.Error);
                loadingLayout.setErrorText(failureResult.getResultInfo());
            } else {
                showToast(failureResult.getResultInfo());
            }
        }
    }

    @Override
    public void onGetBigTypeSuccess(BaseModel<List<DictInfo>> successResult) {
        hsvTypeScroller.setVisibility(View.VISIBLE);
        bigTypeData.clear();
        bigTypeData.addAll(successResult.getData());
        bigTypeData.add(0, new DictInfo("all", "全部车型"));
        bigTypeAdapter.notifyDataSetChanged();
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvTypeChooseGrid.getLayoutParams();
        lp.width = SizeUtils.dp2px(90) * bigTypeData.size();
        nsgvTypeChooseGrid.setLayoutParams(lp);
        nsgvTypeChooseGrid.setNumColumns(bigTypeData.size());
        nsgvTypeChooseGrid.setColumnWidth(SizeUtils.dp2px(90));
    }

    @Override
    public void onGetBigTypeFailure(BaseModel<Object> failureResult) {
        hsvTypeScroller.setVisibility(View.GONE);
    }

    @Override
    public void onGetSmallTypeSuccess(BaseModel<List<DictInfo>> successResult) {
        bigTypeData.get(tempPosition).setChildList(successResult.getData());
        showChooseTypePopup(successResult.getData());
    }

    @Override
    public void onGetSmallTypeFailure(BaseModel<Object> failureResult) {
        if(failureResult.getResultCode() == Constants.PAGE_DATA_EMPTY){
            bigTypeData.get(tempPosition).setChildList(new ArrayList<>());
            chooseSeriesType =  bigTypeData.get(tempPosition).getKey();
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getList(1);
        }else{
            showToast(failureResult.getResultInfo());
        }
    }

    @Override
    public String getSelectYear() {
        if (selectDate != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(selectDate);
            return c.get(Calendar.YEAR) + "";
        }
        return "";
    }

    @Override
    public String getSelectMonth() {
        if (selectDate != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(selectDate);
            int m = (c.get(Calendar.MONTH) + 1);
            return (m > 9 ? m : "0" + m) + "";
        }
        return "";
    }

    @Override
    public String getPriceMin() {
        return choosePrice != null ? choosePrice.getMin() : "";
    }

    @Override
    public String getSeriesType() {
        return chooseSeriesType;
    }

    @Override
    public String getPriceMax() {
        return choosePrice != null ? choosePrice.getMax() : "";
    }

    @OnClick({R.id.tv_choose_time, R.id.tv_choose_price})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_choose_time:
                showChooseTimeDialog();
                break;
            case R.id.tv_choose_price:
                showChoosePricePopup();
                break;
        }
    }

    @Override
    public void onChooseType(String typeId) {
        chooseSeriesType = typeId;
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    private void showChooseTypePopup(List<DictInfo> list) {
        if (customChooseCarTypePopup == null) {
            customChooseCarTypePopup = new CustomChooseCarTypePopup(mContext);
            customChooseCarTypePopup.setListener(this);
        }
        customChooseCarTypePopup.initTypeModel(chooseSeriesType, list);
        new XPopup.Builder(mContext)
                .atView(v_split_line)
                .asCustom(customChooseCarTypePopup)
                .show();
    }

    private void showChooseTimeDialog() {
        if (pvTimePicker == null) {
            Calendar startDate = Calendar.getInstance();
            startDate.setTime(TimeUtils.string2Date("1970-01-01", new SimpleDateFormat("yyyy-MM-dd")));
            Calendar sdate = Calendar.getInstance();
            sdate.setTime(selectDate);
            Calendar endDate = Calendar.getInstance();
            endDate.setTime(TimeUtils.getNowDate());
            pvTimePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date select, View v) {//选中事件回调
                    selectDate = select;
                    tvChooseTime.setText(TimeUtils.date2String(selectDate, new SimpleDateFormat("yyyy年MM月")));
                    loadingLayout.setStatus(LoadingLayout.Loading);
                    mvpPresenter.getList(1);
                }
            })
                    .setType(new boolean[]{true, true, false, false, false, false})
                    .setCancelText("取消")//取消按钮文字
                    .setSubmitText("确定")//确认按钮文字
                    .setContentTextSize(18)
                    .setDividerColor(ContextCompat.getColor(mContext, R.color.c_999999))
                    .setItemVisibleCount(9)
                    .setLineSpacingMultiplier(2.5f)
                    .setTitleColor(ContextCompat.getColor(mContext, R.color.c_666666))
                    .setTitleSize(20)//标题文字大小
                    .setTitleText("选择时间")//标题文字
                    .setTitleColor(ContextCompat.getColor(mContext, R.color.c_333333))//标题文字颜色
                    .setTitleBgColor(ContextCompat.getColor(mContext, R.color.colorWhite))
                    .setSubmitColor(ContextCompat.getColor(mContext, R.color.app_color))//确定按钮文字颜色
                    .setCancelColor(ContextCompat.getColor(mContext, R.color.c_333333))//取消按钮文字颜色
                    .setBgColor(ContextCompat.getColor(mContext, R.color.colorWhite))//滚轮背景颜色 Night mode
                    .setDate(sdate)// 如果不设置的话，默认是系统时间*/
                    .setRangDate(startDate, endDate)//起始终止年月日设定
                    .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                    .isCyclic(false)//是否循环滚动
                    .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                    .isDialog(false)//是否显示为对话框样式
                    .build();
        }
        pvTimePicker.show();
    }

    @Override
    public void onChoosePrice(PriceConditionInfo info) {
        choosePrice = info;
        tvChoosePrice.setText(info.getName());
        loadingLayout.setStatus(LoadingLayout.Loading);
        mvpPresenter.getList(1);
    }

    private void showChoosePricePopup() {
        if (customChoosePricePopup == null) {
            customChoosePricePopup = new CustomChoosePricePopup(mContext);
            customChoosePricePopup.setListener(this);
        }
        customChoosePricePopup.initPriceModel(choosePrice);
        new XPopup.Builder(mContext)
                .atView(llChoosePanel)
                .asCustom(customChoosePricePopup)
                .show();
    }

}
